﻿#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lame/lame.h"

#define INPUT_BUFFER_SIZE 4096 // 假设你的 PCM 数据块大小是 4096 字节  
#define SAMPLE_RATE 44100      // PCM 采样率  
#define CHANNELS 1             // 声道数，单声道为 1，立体声为 2  
#define BITS_PER_SAMPLE 16     // 每个样本的位数  
#define BITRATE 128            // MP3 比特率  

int main(int argc, char** argv)
{
    FILE* wavFile = fopen("test.wav", "rb");
    if (!wavFile)
    {
        perror("Error opening WAV file");
        return -1;
    }

    fseek(wavFile, 44L, 0); //把stream指针移动到离文件开头44字节处；
    FILE* mp3File = fopen("output.mp3", "wb");

    if (!mp3File)
    {
        perror("Error opening mp3 file");
        return -1;
    }

    // 初始化LAME编码器
    lame_t lame = lame_init();
    if (lame == nullptr) { return -1; }

    int ret = 0;
    do
    {
        // 设置编码参数  
        lame_set_in_samplerate(lame, SAMPLE_RATE);
        lame_set_num_channels(lame, CHANNELS);
        lame_set_out_samplerate(lame, SAMPLE_RATE); // 通常输出采样率与输入采样率相同  
        lame_set_brate(lame, BITRATE);
        lame_set_mode(lame, MONO); // 立体声模式  
        lame_set_quality(lame, 0); // 质量设置，范围从 0（最高）到 9（最低）  

        int ret_code = lame_init_params(lame);

        if (ret_code < 0)
        {
            printf("lame_init error:%d", ret_code);
            ret = -2;
            break;
        }

        int pcmBufferSize = INPUT_BUFFER_SIZE / (CHANNELS * sizeof(short int));

        printf("pcmBufferSize: %d",pcmBufferSize);

        short int pcmBuffer[pcmBufferSize];
        memset(pcmBuffer, 0, sizeof(pcmBuffer));

        int mp3BufferSize = lame_get_framesize(lame);
        unsigned char mp3Buffer[mp3BufferSize];
        memset(mp3Buffer, 0, sizeof(mp3Buffer));

        int readBytes = -1, encodedBytes = -1;
        while ((readBytes = fread(pcmBuffer, sizeof(short int), sizeof(pcmBuffer) / sizeof(short int), wavFile)))
        {
            encodedBytes = lame_encode_buffer(lame, pcmBuffer, pcmBuffer, readBytes / (CHANNELS * sizeof(short int)), mp3Buffer, mp3BufferSize);
            if (encodedBytes < 0)
            {
                fprintf(stderr, "Encoding error\n");
                ret = -3;
                break;
            }
            fwrite(mp3Buffer, 1, encodedBytes, mp3File);
        }
        if (ret != 0) { break; }

        // 刷新并写入剩余的 MP3 帧（如果有的话）  
        encodedBytes = lame_encode_flush(lame, mp3Buffer, mp3BufferSize);
        if (encodedBytes > 0)
        {
            fwrite(mp3Buffer, 1, encodedBytes, mp3File);
        }

        return 0;

    } while (0);

    if (lame) { lame_close(lame); }
    if (wavFile) { fclose(wavFile); }
    if (mp3File) { fclose(mp3File); }

    return ret;
}